
using System;
using System.Data;

using Serpis;

namespace PArticulo
{
	public class ArticuloPersister : IPersister
	{
		private const string insertCommand = "insert into articulo (nombre, precio, categoria) values (?nombre, ?precio, ?categoria)";
		private const string updateCommand = "update articulo set nombre=?nombre, precio=?precio, categoria=?categoria where id=?id";
		private const string selectCommand = "select * from articulo where id=?id";
		private const string deleteCommand = "delete from articulo where id=?id";
		
		public void Save(object model)
		{
			Articulo articulo = (Articulo)model;
			
			IDbCommand dbCommand = AppDbConnection.Instance.DbConnection.CreateCommand();
			if (articulo.Id == 0) //insert
				dbCommand.CommandText = insertCommand;
			else { //update
				dbCommand.CommandText = updateCommand;
				dbCommand.AddParameter("id", articulo.Id);
			}
				
			dbCommand.AddParameter("nombre", articulo.Nombre);
			dbCommand.AddParameter("precio", articulo.Precio);
			dbCommand.AddParameter("categoria", articulo.Categoria);
			
			dbCommand.ExecuteNonQuery();
		}
		
		public object Load(Type type, object id)
		{
			
			IDbCommand dbCommand = AppDbConnection.Instance.DbConnection.CreateCommand();
			dbCommand.CommandText = selectCommand;
			dbCommand.AddParameter("id", id);
			
			IDataReader dataReader = dbCommand.ExecuteReader();
			dataReader.Read(); //leemos el primer registro (y único)
			
			Articulo articulo = new Articulo();
			articulo.Id = (long)id;
			articulo.Nombre = (string)dataReader["nombre"];
			articulo.Precio = (decimal)dataReader["precio"];
			articulo.Categoria = dataReader["categoria"] is DBNull ? (long?)null : (long)dataReader["categoria"];
			
			dataReader.Close();
			
			return articulo;
		}
		
		public void Delete(Type type, object id)
		{
			IDbCommand dbCommand = AppDbConnection.Instance.DbConnection.CreateCommand();
			dbCommand.CommandText = deleteCommand;
			dbCommand.AddParameter("id", id);
			
			dbCommand.ExecuteNonQuery();
		}
		
	}
}
